import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class FileManager {
    private static final String DATA_DIR = "data";
    private static final String NOTES_FILE = "notes.txt";
    private static final String CATEGORIES_FILE = "categories.txt";
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public FileManager() {
        // 确保数据目录存在
        File dataDir = new File(DATA_DIR);
        if (!dataDir.exists()) {
            dataDir.mkdirs();
        }
    }

    public String readFile(File file) {
        try {
            return Files.readString(file.toPath(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean writeFile(File file, String content) {
        try {
            Files.writeString(file.toPath(), content, StandardCharsets.UTF_8);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean createBackup(File file) {
        if (!file.exists()) {
            return false;
        }

        try {
            File backupFile = new File(file.getAbsolutePath() + ".bak");
            Files.copy(file.toPath(), backupFile.toPath());
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 保存所有笔记数据
    public boolean saveNotes(Map<String, List<SmartNotepad.NoteItem>> categorizedNotes) {
        try {
            File notesFile = new File(DATA_DIR, NOTES_FILE);
            PrintWriter writer = new PrintWriter(new FileWriter(notesFile, StandardCharsets.UTF_8));

            for (Map.Entry<String, List<SmartNotepad.NoteItem>> entry : categorizedNotes.entrySet()) {
                String category = entry.getKey();
                List<SmartNotepad.NoteItem> notes = entry.getValue();

                for (SmartNotepad.NoteItem note : notes) {
                    // 格式：分类|标题|创建时间|修改时间|内容
                    writer.println(category + "|" +
                            escapeText(note.title) + "|" +
                            note.createTime.format(DATE_FORMAT) + "|" +
                            note.modifyTime.format(DATE_FORMAT) + "|" +
                            escapeText(note.content));
                }
            }

            writer.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 加载所有笔记数据
    public Map<String, List<SmartNotepad.NoteItem>> loadNotes() {
        Map<String, List<SmartNotepad.NoteItem>> categorizedNotes = new HashMap<>();

        File notesFile = new File(DATA_DIR, NOTES_FILE);
        if (!notesFile.exists()) {
            return categorizedNotes;
        }

        try {
            BufferedReader reader = new BufferedReader(new FileReader(notesFile, StandardCharsets.UTF_8));
            String line;

            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty())
                    continue;

                String[] parts = line.split("\\|", 5);
                if (parts.length == 5) {
                    String category = parts[0];
                    String title = unescapeText(parts[1]);
                    LocalDateTime createTime = LocalDateTime.parse(parts[2], DATE_FORMAT);
                    LocalDateTime modifyTime = LocalDateTime.parse(parts[3], DATE_FORMAT);
                    String content = unescapeText(parts[4]);

                    SmartNotepad.NoteItem note = new SmartNotepad.NoteItem();
                    note.title = title;
                    note.content = content;
                    note.createTime = createTime;
                    note.modifyTime = modifyTime;
                    note.category = category;

                    categorizedNotes.computeIfAbsent(category, k -> new ArrayList<>()).add(note);
                }
            }

            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return categorizedNotes;
    }

    // 保存分类列表
    public boolean saveCategories(List<String> categories) {
        try {
            File categoriesFile = new File(DATA_DIR, CATEGORIES_FILE);
            PrintWriter writer = new PrintWriter(new FileWriter(categoriesFile, StandardCharsets.UTF_8));

            for (String category : categories) {
                writer.println(category);
            }

            writer.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 加载分类列表
    public List<String> loadCategories() {
        List<String> categories = new ArrayList<>();

        File categoriesFile = new File(DATA_DIR, CATEGORIES_FILE);
        if (!categoriesFile.exists()) {
            // 返回默认分类
            categories.add("未分类");
            categories.add("工作文档");
            categories.add("学习笔记");
            categories.add("日记日志");
            categories.add("技术文档");
            categories.add("创意写作");
            categories.add("计划安排");
            return categories;
        }

        try {
            BufferedReader reader = new BufferedReader(new FileReader(categoriesFile, StandardCharsets.UTF_8));
            String line;

            while ((line = reader.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    categories.add(line.trim());
                }
            }

            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return categories;
    }

    // 转义文本中的特殊字符
    private String escapeText(String text) {
        if (text == null)
            return "";
        return text.replace("|", "&#124;").replace("\n", "&#10;").replace("\r", "&#13;");
    }

    // 反转义文本
    private String unescapeText(String text) {
        if (text == null)
            return "";
        return text.replace("&#124;", "|").replace("&#10;", "\n").replace("&#13;", "\r");
    }
}